package cn.datawin.task.process;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import cn.datawin.spider.page.Page;
import cn.datawin.task.Rule;
import cn.datawin.task.Task;

public class TypeProcessor extends AbstractProcessor {

	Page page;

	List<Object> list;

	Task task;

	@Override
	public void process(Page page) {
		this.page = page;
		Rule rule = new Rule(task.currentRule());
		super.params = new HashMap<String, String>();
		super.parseRule(rule, page);
		parseTypeUrl(rule);
	}

	public void parseTypeUrl(Rule rule) {
		for (Map<String, String> map : rule.getExpression()) {
			String name = map.get("name");
			String typeUrls = params.remove(name);
			if (StringUtils.isEmpty(typeUrls))	return;
			list = new ArrayList<Object>();
			for (String typeUrl : typeUrls.split("\\^\\|")) {
				if(!StringUtils.isEmpty(rule.getUrlRule())){
					typeUrl = parseUrlRule(rule.getUrlRule(), typeUrl);
				}
				list.add(typeUrl);
			}
		}
	}
	
	public String parseUrlRule(String urlRule,String typeUrl){
		return String.format(urlRule, typeUrl);
	}

	@Override
	public Map<String, String> getParams() {
		return super.params;
	}

	@Override
	public List<Object> getList() {
		return list;
	}

	@Override
	public Page getPage() {
		return page;
	}

	@Override
	public void setTask(Serializable task) {
		this.task = (Task) task;
	}

	@Override
	public Serializable getTask() {
		return task;
	}

}
